import tkinter as tk
from tkinter import messagebox
from logic.json_function import save_json

def save_task(task_dict, task_name, task_due_date, task_description, file_path, task_priority, listbox):
    task_dict[task_name] = {
        'task_due_date': task_due_date,
        'task_description': task_description,
        'task_priority': task_priority
    }
    save_json(file_path, task_dict)
    listbox.insert(tk.END, f"{task_name} priority:{task_priority} due to {task_due_date}")
    messagebox.showinfo("Success", "Task saved successfully!")

def save_task_callback(task_dict, task_name, task_due_date, task_description, file_path, task_priority, listbox):
    if not task_name or not task_due_date or not task_description or not task_priority:
        messagebox.showerror("Error", "All fields are required!")
        return
    save_task(task_dict, task_name, task_due_date, task_description, file_path, task_priority, listbox)

def on_click_button_task_append(task_dict, listbox):
    def save_task_callback_wrapper():
        task_name = entry_task_name.get()
        task_due_date = entry_task_due_date.get()
        task_description = entry_task_description.get()
        task_priority = entry_task_priority.get()
        save_task_callback(task_dict, task_name, task_due_date, task_description, 'information/task_information.json', task_priority, listbox)
        add_window.destroy()

    add_window = tk.Toplevel()
    add_window.title('Add Task')

    label_task_name = tk.Label(add_window, text='Task Name:')
    label_task_name.grid(row=0, column=0, padx=5, pady=5)
    entry_task_name = tk.Entry(add_window)
    entry_task_name.grid(row=0, column=1, padx=5, pady=5)

    label_task_due_date = tk.Label(add_window, text='Due Date:')
    label_task_due_date.grid(row=1, column=0, padx=5, pady=5)
    entry_task_due_date = tk.Entry(add_window)
    entry_task_due_date.grid(row=1, column=1, padx=5, pady=5)

    label_task_description = tk.Label(add_window, text='Description:')
    label_task_description.grid(row=2, column=0, padx=5, pady=5)
    entry_task_description = tk.Entry(add_window)
    entry_task_description.grid(row=2, column=1, padx=5, pady=5)

    label_task_priority = tk.Label(add_window, text='Priority:')
    label_task_priority.grid(row=3, column=0, padx=5, pady=5)
    entry_task_priority = tk.Entry(add_window)
    entry_task_priority.grid(row=3, column=1, padx=5, pady=5)

    button_save = tk.Button(add_window, text='Save', command=save_task_callback_wrapper)
    button_save.grid(row=4, column=0, columnspan=2, padx=5, pady=5)